<template>
  <div class="app-container" ref="appContainer">
    <PropTable
      ref="tableData"
      :loading="loading"
      :columns="column"
      :data="data"
      @reset="reset"
      @onSubmit="onSubmit"
      @add="add"
    >
      <template v-slot:operation="scope">
        <el-button
          type="primary"
          size="small"
          icon="Plus"
          @click="
            router.push({
              name: 'supplierInfo',
              state: { id: scope.row.id },
            })
          "
        >
          添加联系人
        </el-button>
        <el-button
          type="primary"
          size="small"
          icon="View"
          @click="
            router.push({
              name: 'supplierInfo',
              state: { id: scope.row.id },
            })
          "
        >
          详情
        </el-button>
        <!--  <el-button @click="del(scope.row)" type="danger" size="small" icon="Delete">
          删除
        </el-button>-->
      </template>
    </PropTable>

    <el-drawer v-model="dialogVisible" title="新增">
      <el-form
        ref="ruleFormRef"
        :model="newsupplier"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
      >
        <el-form-item label="供应商名称：" prop="supplierName">
          <el-input v-model="newsupplier.supplierName" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="税号：" prop="supplierNumber">
          <el-input v-model="newsupplier.supplierNumber" placeholder="请输入税号" />
        </el-form-item>
        <el-form-item label="供应商等级：" prop="supplierLevel">
          <el-select
            v-model="newsupplier.supplierLevel"
            placeholder="请选择供应商等级"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in supplierLevelList"
              :key="ite.value"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="法定代表人：" prop="supplierPeople">
          <el-input v-model="newsupplier.supplierPeople" placeholder="请输入法定代表人" />
        </el-form-item>
        <el-form-item label="企业类型：" prop="supplierType">
          <el-select
            v-model="newsupplier.supplierType"
            placeholder="请选择企业类型"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in supplierTypeList"
              :key="ite.value"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="注册资本(万元)：" prop="supplierCapital">
          <el-input-number
            v-model="newsupplier.supplierCapital"
            placeholder="请输入注册资本"
            style="width: 220px"
            :precision="2"
            :min="0"
            :max="500000000"
          />
          &nbsp;&nbsp;万元
        </el-form-item>
        <el-form-item label="组织机构代码：" prop="supplierCode">
          <el-input v-model="newsupplier.supplierCode" placeholder="请输入组织机构代码" />
        </el-form-item>
        <el-form-item label="供应商地址：" prop="supplierAddress">
          <el-input v-model="newsupplier.supplierAddress" placeholder="请输入供应商地址" />
        </el-form-item>
        <el-form-item label="所属地区：" prop="supplierArea">
          <el-cascader
            v-model="newsupplier.supplierArea"
            placeholder="请选择所属地区"
            style="width: 100%"
            :options="regionData"
          />
        </el-form-item>
        <el-form-item label="所属行业：" prop="supplierIndustry">
          <el-select
            v-model="newsupplier.supplierIndustry"
            placeholder="请输入所属行业"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in industryList"
              :key="ite.value"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="电话：" prop="supplierPhone">
          <el-input v-model="newsupplier.supplierPhone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="备注：" prop="supplierRemark">
          <el-input v-model="newsupplier.supplierRemark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addsupplier(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup name="comprehensive">
  import { ref, reactive, onMounted, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import PropTable from '@/components/Table/PropTable/index.vue'
  import { regionData, codeToText } from 'element-china-area-data'
  import {
    postSupplierSearch,
    deleteSupplierById,
    postSupplier,
  } from '@/api/controller/supplier-controller/index'
  import {
    getSysIndustryList,
    getSysLevelList,
    getSysSupplierTypeList,
  } from '@/api/controller/sys-user-controller/index'
  import { useRouter } from 'vue-router'
  const router = useRouter()
  const loading = ref(true)
  const appContainer = ref(null)

  const column = ref([
    { name: 'supplierName', label: '供应商名称', inSearch: true, valueType: 'input', width: 200 },
    { name: 'supplierNumber', label: '税号', inSearch: true, valueType: 'input', width: 200 },
    {
      name: 'supplierLevel',
      label: '供应商等级',
      inSearch: true,
      options: [],
      valueType: 'select',
      width: 120,
    },
    { name: 'supplierPeople', label: '法定代表人', valueType: 'input', width: 120 },
    {
      name: 'supplierType',
      label: '企业类型',
      inSearch: true,
      options: [],
      valueType: 'select',
      width: 200,
    },
    { name: 'supplierArea', label: '所属地区', valueType: 'input', width: 180 },
    {
      name: 'supplierIndustry',
      label: '所属行业',
      inSearch: true,
      options: [],
      valueType: 'select',
      width: 180,
    },
    { name: 'supplierState', label: '供应商状态', valueType: 'input', width: 120 },
    { name: 'supplierPhone', label: '电话', valueType: 'input', width: 160 },
    { name: 'supplierRemark', label: '备注', valueType: 'input', width: 160 },
    { name: 'operation', slot: true, fixed: 'right', width: 210, label: '操作', type: false },
  ])
  const data = ref(null)

  const formSize = ref('default')
  const ruleFormRef = ref<FormInstance>()

  const rules = reactive({
    supplierName: [
      { required: true, message: '请输入供应商名称', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    supplierNumber: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
    supplierLevel: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
    supplierPeople: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
    supplierType: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
    supplierCapital: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
    supplierCode: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
    supplierAddress: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
    supplierIndustry: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
    supplierState: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
    supplierPhone: [
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
      {
        pattern: /^(1[3456789]\d{9}|0\d{2,3}-\d{7,8})$/,
        message: '请输入正确的电话格式',
        trigger: 'blur',
      },
    ],
    supplierRemark: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
  })

  const dialogVisible = ref(false)
  const tableData = ref(null)

  // 打开新增弹窗
  const newsupplier = ref({
    supplierName: null,
    supplierNumber: null,
    supplierLevel: null,
    supplierPeople: null,
    supplierType: null,
    supplierCapital: null,
    supplierCode: null,
    supplierAddress: null,
    supplierArea: null,
    supplierIndustry: null,
    supplierState: null,
    supplierPhone: null,
    supplierRemark: null,
    operation: null,
  })
  const add = () => {
    for (let key in newsupplier.value) {
      newsupplier.value[key] = null
    }
    dialogVisible.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }

  //新增
  const addsupplier = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        let a = codeToText[newsupplier.value.supplierArea[0]]
        let b = codeToText[newsupplier.value.supplierArea[1]]
        let c = codeToText[newsupplier.value.supplierArea[2]]
        newsupplier.value.supplierArea = a + '/' + b + '/' + c
        let result = await postSupplier(newsupplier.value, { loading: true })
        if (result.code === 200) {
          try {
            loading.value = true
            const result = await postSupplierSearch(tableData.value?.formInline)
            data.value = result.data
            dialogVisible.value = false
            ElMessage.success('添加成功')
          } finally {
            loading.value = false
          }
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }

  // 删除当前项
  const del = async (row) => {
    ElMessageBox.confirm('你确定要删除当前项吗?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    })
      .then(async () => {
        const result = await deleteSupplierById({ id: row.id })
        if (result.code === 200) {
          loading.value = true
          const result = await postSupplierSearch(tableData.value?.formInline)
          data.value = result.data
          dialogVisible.value = false
          loading.value = false
          ElMessage.success('删除成功')
        }
      })
      .catch(() => {
        console.log('错误')
      })
  }
  //重置搜索条件
  const reset = async () => {
    try {
      loading.value = true
      let pageInfo = {
        pageNum: 1,
        pageSize: 15,
      }
      const result = await postSupplierSearch(pageInfo)
      data.value = result.data
    } finally {
      loading.value = false
    }
  }
  //搜索
  const onSubmit = async (val) => {
    try {
      loading.value = true
      const result = await postSupplierSearch(val)
      data.value = result.data
    } finally {
      loading.value = false
    }
  }
  //初始化
  const supplierTypeList = ref([])
  const industryList = ref([])
  const supplierLevelList = ref([])
  onMounted(async () => {
    try {
      loading.value = true
      let pageInfo = {
        pageNum: 1,
        pageSize: 15,
      }
      getSysSupplierTypeList().then((res) => {
        supplierTypeList.value = res.data
        column.value[4].options = res.data
      })
      getSysIndustryList().then((res) => {
        industryList.value = res.data
        column.value[9].options = res.data
      })
      getSysLevelList().then((res) => {
        supplierLevelList.value = res.data
        column.value[2].options = res.data
      })
      let result = await postSupplierSearch(pageInfo)
      data.value = result.data
    } finally {
      loading.value = false
    }
  })
</script>

<style scoped>
  .edit-input {
    padding-right: 100px;
  }
  .app-container {
    flex: 1;
    display: flex;
    width: 100%;
    padding: 16px;
    box-sizing: border-box;
  }
  .cancel-btn {
    position: absolute;
    right: 15px;
    top: 10px;
  }
</style>
